/*
Copyright (C) 2011 by the PSVN Research Group, University of Alberta
*/

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <dlfcn.h>
#include <assert.h>
#include <ctype.h>
#include "psvn_game_so.h"
#include "pdb.h"

pdb_t* read_pdb(const char* filename, const compiled_game_so_t* game)
{
    pdb_t* data;
    data = (pdb_t*) malloc (sizeof(pdb_t));
    data->abst = read_so_abstraction_from_file( filename, game );
    if( data->abst == NULL ) {
        fprintf( stderr, "could not read abstraction file %s\n", filename );
        return NULL;
    }
    /* get map filename by changing extension from ".abst" to ".table" */
    char map_filename[1024];
    strcpy(map_filename, filename);
    strcpy(strstr(map_filename, ".abst"), ".table");
    
    /* read the map */
    FILE* file = fopen( map_filename, "r" );
    if( file == NULL ) {
        fprintf( stderr, "could not open abstraction table %s\n", map_filename);
        destroy_so_abstraction( data->abst, game );
        free( data );
        return NULL;
    }
    data->map = read_so_state_map( file, game );
    fclose( file );
    if( data->map == NULL ) {
        fprintf( stderr, "could not read abstraction table %s\n", map_filename);
        destroy_so_abstraction( data->abst, game );
        free( data );
        return NULL;
    }
    data->temp_state = new_so_state( game );
    return data;
}

void destroy_pdb(pdb_t* data, const compiled_game_so_t* game)
{
    destroy_so_abstraction(data->abst, game);
    destroy_so_state_map(data->map, game);
    destroy_so_state(data->temp_state);
    free(data);
}

int pdb_lookup(const pdb_t* abst, const void* state,
               const compiled_game_so_t* game)
{
    so_abstract_state( abst->abst, state, abst->temp_state, game );
    int *h;
    h = so_state_map_get( abst->map, abst->temp_state, game );
    if (h == NULL)
        return 0;
    return *h;
}
